package com.ht.api.util;

import org.springframework.stereotype.Component;

/**
 * 雪花算法工具类
 * @author 77290
 * @time 2024年3月21日 17:38:54
 */
@Component
public class SnowflakeIdGenerator{
	private static final long START_TIMESTAMP = 1609459200000L; // 设置起始时间为2021年1月1日零点

	private static final int WORKER_ID_BITS = 5; // worker id所占位数
	private static final int DATACENTER_ID_BITS = 5; // datacenter id所占位数
	private static final int SEQUENCE_BITS = 12; // sequence序列所占位数

	private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS); // max worker id值
	private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS); // max data center id值

	private static final long WORKER_ID_SHIFT = SEQUENCE_BITS; // worker id左移位数
	private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; // data center id左移位数
	private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS; // timestamp左移位数

	private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS); // sequence mask值

	private long lastTimestamp = -1L; // 上次生成id的时间截
	private long sequence = 0L; // 当前sequence值

	private final long workerId; // worker id
	private final long dataCenterId; // data center id
	
	public SnowflakeIdGenerator() {
		this.workerId = 0;
		this.dataCenterId = 0;
	}

	public SnowflakeIdGenerator(long workerId, long dataCenterId) {
		if (workerId < 0 || workerId > MAX_WORKER_ID) {
			throw new IllegalArgumentException("Worker ID can't be greater than " + MAX_WORKER_ID + " or less than 0");
		}

		if (dataCenterId < 0 || dataCenterId > MAX_DATACENTER_ID) {
			throw new IllegalArgumentException(
					"Data Center ID can't be greater than " + MAX_DATACENTER_ID + " or less than 0");
		}

		this.workerId = workerId;
		this.dataCenterId = dataCenterId;
	}

	public synchronized long nextId() {
		long currentTimeMillis = System.currentTimeMillis();

		if (currentTimeMillis < lastTimestamp) {
			throw new RuntimeException(
					"Clock moved backwards. Refusing to generate id for " + (lastTimestamp - currentTimeMillis));
		}

		if (currentTimeMillis == lastTimestamp) {
			sequence = (sequence + 1) & SEQUENCE_MASK;

			if (sequence == 0) {
				currentTimeMillis = getNextMillis(lastTimestamp);
			}
		} else {
			sequence = 0L;
		}

		lastTimestamp = currentTimeMillis;

		return ((currentTimeMillis - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT) | (dataCenterId << DATACENTER_ID_SHIFT)
				| (workerId << WORKER_ID_SHIFT) | sequence;
	}

	private long getNextMillis(final long lastTimestamp) {
		long timestamp = System.currentTimeMillis();

		while (timestamp <= lastTimestamp) {
			timestamp = System.currentTimeMillis();
		}

		return timestamp;
	}
	
	public static void main(String[] args) {
		SnowflakeIdGenerator sf = new SnowflakeIdGenerator();
		for (int i=0; i<100; i++) {
			System.err.println(sf.nextId());
		}
	}
}
